import React from 'react'
import {Button, Result} from 'antd'

interface ErrorBoundaryState {
  hasError: boolean
  error?: any
}

export default class ErrorBoundary extends React.Component<React.PropsWithChildren<{}>, ErrorBoundaryState> {
  constructor(props: React.PropsWithChildren<{}>) {
    super(props)
    this.state = { hasError: false, error: null }
  }

  static getDerivedStateFromError(error: any) {
    return { hasError: true, error }
  }

  componentDidCatch(error: any, info: any) {
    // 可替换为更完善的日志上报
    console.error('App crashed:', error, info)
  }

  handleReload = () => {
    window.location.reload()
  }

  render() {
    if (this.state.hasError) {
      return (
        <div style={{ height: '100vh', display: 'grid', placeItems: 'center' }}>
          <Result
            status="error"
            title="应用发生错误"
            subTitle={String(this.state.error?.message || '请刷新或重启应用')}
            extra={<Button type="primary" onClick={this.handleReload}>刷新页面</Button>}
          />
        </div>
      )
    }
    return this.props.children
  }
}